package com.aacar.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aacar.dto.Header;
import com.aacar.entity.CheckCode;
import com.aacar.interceptor.TranFailException;
import com.aacar.service.CheckCodeService;
import com.aacar.utils.DateUtil;
import com.aacar.utils.ErrorCodeConsField;
import com.aacar.utils.ErrorInfoUtil;
import com.aacar.utils.Pphconfig;
import com.aacar.utils.ResultInfoUtil;
import com.alibaba.fastjson.JSONObject;

public abstract class ValidController {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	protected Header getMobileHead(HttpServletRequest request)throws TranFailException{
		logger.info("#### RequestHeader-mobilehead:"+ JSONObject.toJSONString(request.getHeader("mobilehead")));
		Header mobileHead = null;
		try{
			mobileHead = JSONObject.parseObject(request.getHeader("mobilehead"),Header.class);
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
		    logger.error("####  mobilehead 转换失败  MobileHead 对象失败");
		    throw new TranFailException(ErrorCodeConsField.ERROR_MSG_10217, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10217));
		}
		return mobileHead;
	}
	
	
	/**
	 * 检验验证码
	 * @param code
	 * @param mobile
	 * @param type 1为注册 2为忘记密码
	 * @return
	 */
	protected Object checkCode(CheckCodeService checkCodeService,String code,String mobile,String type) {
		
		CheckCode checkCode = new CheckCode();
		checkCode.setMobile(mobile);//手机号
		checkCode.setType(type); 
		CheckCode tempCheckCode = checkCodeService.getCheckCode(checkCode);
	   
		if(tempCheckCode != null){
			Date modifyTime = tempCheckCode.getModifyTime();
			Date timeoutDate = DateUtil.addDateMinut(modifyTime, 10);
			Date nowDate = DateUtil.getNowDate();
		
			if(nowDate.getTime()<timeoutDate.getTime()){
				if(!tempCheckCode.getCheckCode().equals(code)){
					 //验证码错误			
					return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10101, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10101));
				}
			}else{
				//您输入的验证已过期，请重新获取
	    		return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10102, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10102));
			}
		}else{
			//验证码错误
			return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10101, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10101));
		}
		
		return ResultInfoUtil.setSuccessInfo(1);
	}
}
